'use strict';
const db = uniCloud.database();
const dbCmd = db.command;
const $ = dbCmd.aggregate;
let myCloud = uniCloud.init({
	provider: 'tencent',
	spaceId: 'tcb-fy6f7f4nm7mhifi-6c366c810511'
})
const wmzWechatSdk = myCloud.importObject('wmz-wechat-sdk')
exports.main = async (event, context) => {
	let rechargeDatas = await db.collection('wmzmall-shopie').where({
		is_deliver: dbCmd.exists(false),
		auto_deliver: true,
		way:'微信支付'
	}).limit(100).orderBy('create_time', 'desc').get()
	rechargeDatas = rechargeDatas.data
	console.log(rechargeDatas.length+"条待发货")
	for (var i in rechargeDatas) {
		console.log(rechargeDatas[i])
		let user = await db.collection('uni-id-users').doc(rechargeDatas[i].creator_id).get()
		user = user.data[0]
		let authorizerToken = await wmzWechatSdk.getAuthorizerToken(rechargeDatas[i].app_id)
		console.log(authorizerToken)
		if (authorizerToken.code === 200) {
			authorizerToken = authorizerToken.data
			let url = "https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info"
			url = url + "?access_token=" + authorizerToken
			let res = await wmzWechatSdk.wechatRequestCommon({
				url: url,
				data: {
					logistics_type: 3,
					delivery_mode: 'UNIFIED_DELIVERY',
					shipping_list: [{
						item_desc: rechargeDatas[i].title
					}],
					upload_time: new Date(),
					order_key: {
						order_number_type: 2,
						transaction_id: rechargeDatas[i].order_no
					},
					payer: {
						openid: user.openid
					}
			
				}
			})
			if (res.code === 200) {
				await db.collection('wmzmall-shopie').doc(rechargeDatas[i]._id).update({
					is_deliver: true
				})
			}else{
				await db.collection('wmzmall-shopie').doc(rechargeDatas[i]._id).update({
					deliver_error: res.msg
				})
			}
		} else {
			await db.collection('wmzmall-shopie').doc(rechargeDatas[i]._id).update({
				deliver_error: authorizerToken.msg
			})
		}
	}
	return event
};